package com.zsc.wxm.ysh.anjo.member.service.impl;

import com.zsc.wxm.ysh.anjo.member.cache.MemberCacheService;
import com.zsc.wxm.ysh.anjo.member.model.Member;
import com.zsc.wxm.ysh.anjo.member.service.PermissionService;
import com.zsc.wxm.ysh.anjo.model.CurrentUser;
import com.zsc.wxm.ysh.anjo.model.SecurityUser;
import com.zsc.wxm.ysh.anjo.result.CodeEnum;
import com.zsc.wxm.ysh.anjo.service.base.annotations.LoggerHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/2/8 15:48
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private MemberCacheService memberCacheService;

    @Resource
    private PermissionService permissionService;

    @LoggerHandler(desc = "登录日志")
    @Override
    public UserDetails loadUserByUsername(String phone) {
        //根据手机号查询
        Member user = memberCacheService.getUserByPhone(phone);
        if (user == null) {
            throw new UsernameNotFoundException(CodeEnum.USER_IS_NOT_EXIT.getMessage());
        }
        CurrentUser currentUser = new CurrentUser();
        BeanUtils.copyProperties(user,currentUser);
        //根据用户查询用户的权限列表
        List<String> permissionValueList = permissionService.selectPermissionValueByMemberId(user.getId());
        SecurityUser securityUser = new SecurityUser();
        securityUser.setCurrentUser(currentUser);
        securityUser.setPermissionList(permissionValueList);
        return securityUser;
    }
}
